import React from "react";
import { connect } from "react-redux";
import cookie from "react-cookies";
import { Modal } from "antd";
import { receiveWebsocketData } from "./reducer.js";
//今日告警总数
import { getodayWarningStatisticsRequest } from "../Board/store/action";
//告警统计
import { getAlarmStatisticsRequest } from "../Board/store/action";
//告警占比
import { getwarningRegionProportionRequest } from "../Board/store/action";
//最近10条告警数据
import { getatestTenWarningRequest } from "../Board/store/action";
//告警趋势
import { getmonthWarningStatisticsRequest } from "../Board/store/action";
import { getAllDataRequest } from "../Board/store/action";
import CheckLogin from "../CheckLogin/index.jsx";
import { isloginRequest } from "../../pages/App/store/action";
//获取巡线工告警
import { getWarningByASTTMD } from "../../pages/Lineinspector/store/action";
//  获取本地token 默认为undefined
import { getAllCamera } from "../Board/components/Center/request/action";

const token = cookie.load("x-auth-token");
//刷新页面时候移除弹框的标识
sessionStorage.removeItem("websocketReconnect");

var Socket,
  lockReconnect = false,
  WS_IP,
  websocketStatus = true,
  _id,
  // 连发送心跳的次数
  countHeart = 0,
  //  重连的标识
  reconnectFlag = true;

const Websocket = ({
  url,
  id,
  getodayWarningStatistics,
  getAlarmStatistics,
  getAllCamera,
  getwarningRegionProportion,
  getWarningByASTTMD,
  checkLoginRequest,
  getatestTenWarning,
  getmonthWarningWarning,
  getmonthWarningStatisticsRequest,
  getAllData,
}) => {
  _id = id;
  React.useEffect(() => {
    WS_IP = "ws://127.0.0.1:8088/wsresult?" + token;
    WS_Connect();

    return () => {
      try {
        websocketStatus = false;
        if (heartCheck.timeoutObj) {
          clearTimeout(heartCheck.timeoutObj);
          clearTimeout(heartCheck.serverTimeoutObj);
          heartCheck.timeoutObj = null;
          heartCheck.serverTimeoutObj = null;
        }
        Socket.close();
        Socket = null;
      } catch (e) {
        console.log("e");
      }
    };
  }, [url]);
  const WS_Connect = () => {
    try {
      Socket = new WebSocket(WS_IP);
      initWS();
    } catch (e) {
      console.log("创建webSocket失败，重连");
      // 此处调用重连方法
      websocketReconnect();
    }
  };

  //  初始化
  const initWS = () => {
    Socket.onopen = function () {
      heartCheck.reset().start();
    };
    Socket.onmessage = function (info) {
      console.log("websocket心跳数据", JSON.parse(info.data));
      const data = JSON.parse(info.data);
      heartCheck.reset().start();
      if (data.type === "pushWarningAdmin") {
        if (_id === "websocketboard") {
          //  所有告警信息和摄像头信息
          getAllData();
        }
      } else if (data.type === "checkLogin") {
        checkLoginRequest();
      } else if (data.type === "feedBack") {
        getAlarmStatistics();
      } else if (data.type === "downServer") {
        window.location.href = "/";
      }

      if (data.type === "pushWarningPatroller") {
        if (_id === "Lineinspectoralarm") {
          //页数
          let page = {
            pageIndex: 0,
            pageSize: 1000,
          };
          getWarningByASTTMD(page);
        }
      }
    };
    // 后台服务异常不断调用这两个方法
    Socket.onerror = function (event) {
      console.log(
        "websocket 异常断开: " +
          event.code +
          " " +
          event.reason +
          " " +
          event.wasClean +
          event
      );
      if (heartCheck.timeoutObj) {
        clearTimeout(heartCheck.timeoutObj);
        clearTimeout(heartCheck.serverTimeoutObj);
      }
      websocketReconnect();
    };
    Socket.onclose = function (event) {
      console.log(
        "websocket 断开: " +
          event.code +
          " " +
          event.reason +
          " " +
          event.wasClean +
          event
      );
      if (heartCheck.timeoutObj) {
        clearTimeout(heartCheck.timeoutObj);
        clearTimeout(heartCheck.serverTimeoutObj);
      }
      if (websocketStatus) {
        websocketReconnect();
      }
    };
  };
  //  重连方法
  const websocketReconnect = () => {
    // 重连时就将心跳的发送次数设置为0，重新进行判断
    countHeart = 0;
    reconnectionPrompt();
    if (lockReconnect) {
      // 是否已经执行重连
      return;
    }

    lockReconnect = true;
    tt && clearTimeout(tt);
    // 没连接上会一直重连，设置延迟避免请求过多
    var tt = setTimeout(function () {
      // Socket对象置为空
      Socket = null;

      let reconnect =
        sessionStorage.getItem("websocketReconnect") == null
          ? "1"
          : sessionStorage.getItem("websocketReconnect") + "1";
      sessionStorage.setItem("websocketReconnect", reconnect);

      console.log("断线重连中，请稍后。。。。。。" + new Date().getTime());
      WS_Connect();
      lockReconnect = false;
    }, 1000); // 时间代表为3s中延迟
  };

  //  断线弹框
  const reconnectionPrompt = () => {
    if (!reconnectFlag) {
      sessionStorage.removeItem("websocketReconnect");
    }
    if (sessionStorage.getItem("websocketReconnect") == null) {
      return;
    }
    // 5次断线重连后弹框
    if (sessionStorage.getItem("websocketReconnect").length === 5) {
      //  弹框后将标识设置为fasle，当弹框后还在重连的情况时，则不允许再次弹框
      reconnectFlag = false;
      //  弹框延迟1分钟
      let secondsToGo = 60;
      const modal = Modal.error({
        title: "服务器连接断开",
        content: `${secondsToGo} 秒后自动关闭...`,
        okText: "关闭",
        okType: "danger",
        onOk: () => {
          clearInterval(timer);
          sessionStorage.removeItem("websocketReconnect");
          reconnectFlag = true;
        },
      });
      const timer = setInterval(() => {
        secondsToGo -= 1;
        modal.update({
          content: `${secondsToGo} 秒后自动关闭...`,
        });
      }, 1000);
      setTimeout(() => {
        clearInterval(timer);
        // Modal.destroyAll();
        sessionStorage.removeItem("websocketReconnect");
        modal.destroy();
        //  弹框关闭后将重连标识重新设置
        reconnectFlag = true;
      }, secondsToGo * 1000);
    } else if(sessionStorage.getItem("websocketReconnect").length > 7) {
      sessionStorage.removeItem("websocketReconnect");
      reconnectFlag = true;
    }
  };
  // 心跳
  var heartCheck = {
    timeout: 2000,
    timeoutObj: null,
    serverTimeoutObj: null,
    reset: function () {
      if (this.timeoutObj) {
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
      }
      return this;
    },
    start: function () {
      var self = this;
      self.timeoutObj = setTimeout(function () {
        //  心跳数据发送
        const data = {
          type: "heart",
          data: { message: "心跳" },
          from: token,
        };
        try {
          Socket.send(JSON.stringify(data));
          // 有心跳数据时延迟2秒清空弹框
          setTimeout(() => {
            Modal.destroyAll();
          }, 2000);
          // 连续发送10条心跳数据后则清空弹框告警
          countHeart++;
          if (countHeart > 10) {
            sessionStorage.removeItem("websocketReconnect");
          }
          // console.log('00000000000000000000000000');
          // 判断解决后台突然关闭 Socket关闭报错 WebSocket is already in CLOSING or CLOSED state
          self.serverTimeoutObj = setTimeout(function () {
            // console.log('1111111111111111111111111');
            //如果onclose会执行websocketReconnect，我们执行Socket.close()就行了.
            //如果直接执行websocketReconnect 会触发onclose导致重连两次
            Socket.close();
            // 前端突然断网 会关闭Socket 连上网络后会进行重连
            websocketReconnect();
          }, self.timeout);
        } catch (e) {
          Socket = null;
          websocketReconnect();
        }
      }, self.timeout);
    },
  };
  return null;
};

const mapDispatchToProps = (dispatch) => ({
  setWebsocketData(data) {
    dispatch(receiveWebsocketData(data));
  },
  //  所有告警信息和摄像头信息
  getAllData() {
    dispatch(getAllDataRequest());
  },
  //今日告警
  getodayWarningStatistics() {
    dispatch(getodayWarningStatisticsRequest());
  },
  //告警统计
  getAlarmStatistics() {
    dispatch(getAlarmStatisticsRequest());
  },
  //告警占比
  getwarningRegionProportion() {
    dispatch(getwarningRegionProportionRequest());
  },
  //最近10条告警数据
  getatestTenWarning() {
    dispatch(getatestTenWarningRequest());
  },
  //最近告警趋势
  getmonthWarningWarning() {
    dispatch(getmonthWarningStatisticsRequest());
  },
  //巡线工告警
  getWarningByASTTMD(data) {
    dispatch(getWarningByASTTMD(data));
  },

  //判断登录状态
  checkLoginRequest() {
    dispatch(isloginRequest());
  },
  //获取摄像机信息
  getAllCamera() {
    dispatch(getAllCamera());
  },
});
export default connect(null, mapDispatchToProps)(Websocket);
